﻿#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include "JZDataBase.h"

JZDataBase::JZDataBase()
{
    // 初始化数据库连接
    m_db = QSqlDatabase::addDatabase("QSQLITE");    
}

JZDataBase::~JZDataBase()
{
    if (m_db.isOpen()) {
        m_db.close();
    }
}

QSqlDatabase* JZDataBase::database()
{
    return &m_db;
}

bool JZDataBase::open(QString path)
{
    m_db.setDatabaseName(path);
    if (!m_db.open())
    {
        qDebug() << "Open database failed.";
        return false;
    }
    return true;
}

void JZDataBase::close()
{
    m_db.close();
}

int JZDataBase::rowCount(const QString& tableName) {
    QSqlQuery query(m_db);
    QString queryStr = "SELECT COUNT(*) FROM " + tableName;
    if (query.exec(queryStr) && query.next()) {
        return query.value(0).toInt();
    }
    qDebug() << "Failed to get table length for " << tableName << ": " << query.lastError().text();
    return -1;
}

QList<QSqlRecord> JZDataBase::selectRow(const QString& tableName, const JZDbCondition& condition) {
    QList<QSqlRecord> result;
    QString queryStr = QString("SELECT * FROM %1 WHERE %3").arg(tableName,condition.condition());
    QSqlQuery query(m_db);
    if (query.exec(queryStr)) 
    {
        while (query.next()) 
        {
            result.append(query.record());
        }
    }
    return result;
}

bool JZDataBase::insertRow(const QString& tableName, const QSqlRecord& data) {
    QString columns;
    QString values;
    QList<QVariant> bindValues;
    for (int i = 0; i < data.count(); ++i) {
        if (!columns.isEmpty()) {
            columns += ", ";
            values += ", ";
        }
        columns += data.fieldName(i);
        values += ":" + data.fieldName(i);
        bindValues.append(data.value(i));
    }
    QString queryStr = QString("INSERT INTO %1 (%2) VALUES (%3)").arg(tableName,columns,values);
    QSqlQuery query(m_db);
    query.prepare(queryStr);
    for (int i = 0; i < data.count(); ++i) {
        query.bindValue(":" + data.fieldName(i), data.value(i));
    }
    return query.exec();
}

bool JZDataBase::updateRow(const QString& tableName, const QSqlRecord& data, const JZDbCondition& condition) {
    QString setClause;
    for (int i = 0; i < data.count(); ++i) {
        if (!setClause.isEmpty()) {
            setClause += ", ";
        }
        setClause += data.fieldName(i) + " = :" + data.fieldName(i);
    }
    QString queryStr = QString("UPDATE %1 SET %2 WHERE %3").arg(tableName,setClause,condition.condition());
    QSqlQuery query(m_db);
    query.prepare(queryStr);
    for (int i = 0; i < data.count(); ++i) {
        query.bindValue(":" + data.fieldName(i), data.value(i));
    }
    return query.exec();
}

bool JZDataBase::deleteRow(const QString& tableName, const JZDbCondition& condition) {
    if (!m_db.isOpen()) {
        return false;
    }

    QSqlQuery query(m_db);
    QString deleteQuery = QString("DELETE FROM %1 WHERE %2").arg(tableName,condition.condition());
    if (!query.exec(deleteQuery)) {
        return false;
    }

    return true;
}

bool JZDataBase::hasTable(const QString& tableName)
{
    if (m_db.record(tableName).isEmpty())
        return false;

    return true;
}

void JZDataBase::createTable(const JZDbTable& table) {
    if (!m_db.isOpen()) {
        qDebug() << "Database is not open. Cannot create table.";
        return;
    }

    QString createTableQuery = table.generateCreateTableQuery();
    QSqlQuery query(m_db);
    if (!query.exec(createTableQuery)) {
        qDebug() << "Failed to create table: " << query.lastError().text();
    }
}

void JZDataBase::removeTable(const QString& tableName)
{
    // 创建 SQL 查询
    QSqlQuery query;
    QString sql = QString("DROP TABLE IF EXISTS '%1'").arg(tableName);

    // 执行查询
    if (!query.exec(sql)) {
        qDebug() << "Error dropping table:" << query.lastError().text();
    }
}